package CouponService

import (
	"context"
	"gdshop-back-end-go/client-api/app/response/MemberResp"
	toolsDb "gdshop-back-end-go/common/db"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/util/gconv"
	"time"
)

// GetMyAvailable 获取我未使用的优惠券
func GetMyAvailable(ctx context.Context, memberId int) ([]*MemberResp.MemberCoupon, error) {
	var cList []*MemberResp.MemberCoupon
	err := toolsDb.GetUnSafaTable(ctx, "member_coupon").As("mc").LeftJoin(
		"coupon c", "mc.coupon_id = c.id").Fields("c.*,mc.id AS mc_id").Where(
		"mc.delete_at < 1 AND mc.member_id = ? AND mc.use_time < 1 AND (mc.expires_time=0 OR mc.expires_time >= ?)",
		memberId, time.Now().Unix()).Structs(&cList)
	if err != nil {
		return nil, err
	}

	// 处理 use_src_ids 字段
	for _, item := range cList {
		if len(item.UseSrcIdsStr) < 1 {
			continue
		}
		json, err := gjson.LoadContent(item.UseSrcIdsStr)
		if err != nil {
			return nil, err
		}
		if !json.IsNil() {
			tmps := []int{}
			for _, jj := range json.Array() {
				tmps = append(tmps, gconv.Int(jj))
			}
			item.UseSrcIdsIntArr = tmps
		}
	}

	return cList, nil
}
